//! parse config
//!
//! then do tasks

use std::io::prelude::*;

use crate::utils::*;
use crate::{cli::Config, http::Controller};
use console::style;

/// task controller
#[derive(Debug)]
pub struct Task<'a> {
    /// cite for config
    pub config: &'a Config,
}

/// implement basic functions
impl<'a> Task<'a> {
    /// get config from cli::config
    #[inline]
    pub fn from_config(config: &'a Config) -> Self {
        Task { config }
    }

    pub async fn start(&self) {
        let controller = Controller::from(self);

        if self.config.scan {
            controller.scan();
        } else if self.config.view {
            let html = controller.view();
            html.split("\n").for_each(|s| println!("{}", s));

            if let Some(ref path) = self.config.file {
                let mut file = std::fs::File::create(path)
                    .debug_error(self.config.debug)
                    .throw_then(|_| {
                        crate::errorln!(
                            "Opening FILE[{}] failed",
                            style(path.to_str().unwrap()).cyan().bold()
                        )
                    });

                file.write_all(html.as_bytes())
                    .debug_error(self.config.debug)
                    .throw_err(format!(
                        "Writting FILE[{}] file failed",
                        style(path.to_str().unwrap()).cyan().bold(),
                    ));

                println!(
                    "{} Write data into [{}] successfully\n",
                    style("SUCCESS").cyan().bold(),
                    style(path.to_str().unwrap()).cyan().bold()
                );
            }
        } else {
            controller.ping();
        }
    }
}
